package com.yaozheng.vocationaltraining.adapter;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import com.yaozheng.vocationaltraining.fragment.ItemHomeNewsImageFragment;
import com.yaozheng.vocationaltraining.fragment.ItemHomeNewsImageFragment_;
import com.yaozheng.vocationaltraining.utils.LogUtils;
import com.yaozheng.vocationaltraining.utils.TypeUtils;

import net.sf.json.JSONArray;

import java.util.List;

/**
 * 主页新闻图片
 *
 * @author Administrator
 */
public class HomeNewsImageAdapter extends FragmentPagerAdapter {
    JSONArray focusJsonArray;
    FragmentManager fm;

    public HomeNewsImageAdapter(FragmentManager fm) {
        super(fm);
        this.fm = fm;
    }

    public void setFocusJsonArray(JSONArray focusJsonArray) {
        this.focusJsonArray = focusJsonArray;
        update();
    }

    @Override
    public Fragment getItem(int position) {
        ItemHomeNewsImageFragment imageFragment = ItemHomeNewsImageFragment_
                .builder().build();
        Bundle args = new Bundle();
        args.putInt("position", position);
        args.putString("imageUrl", TypeUtils.getJsonString(focusJsonArray, position));
        imageFragment.setArguments(args);
        return imageFragment;
    }

    public void update() {
        List<Fragment> fragmentList = fm.getFragments();
        for (int i = 0; i < fragmentList.size(); i++) {
            Fragment fragment = fragmentList.get(i);
            if (fragment instanceof ItemHomeNewsImageFragment) {
                ItemHomeNewsImageFragment imageFragment = (ItemHomeNewsImageFragment) fragment;
                int position = imageFragment.getPosition();
                imageFragment.setImageUrl(TypeUtils.getJsonString(focusJsonArray, position));
            }
        }
    }

    @Override
    public int getCount() {
        return 3;
    }
}